<!-- pages/index/index.vue -->
<script>
  export default { name: 'IndexPage' }
</script>

<script setup>
  import { computed, ref, onMounted, watch, nextTick } from 'vue'
  import FeedList from './components/feed-list.vue'
  import DoctorList from './components/doctor-list.vue'
  import { homePageDocApi, patientHomeKnowledgeApi } from '@/services/doctor.js'
  // ;(async () => {
  //   const res = await uniCloud.callFunction({
  //     name: 'qq-map',
  //   })
  //   console.log(res, '云函数返回的数据2222')
  // })()

  // 获取安全区域数据
  const { safeAreaInsets } = uni.getSystemInfoSync()

  // 标签页索引值
  const tabIndex = ref(0)

  // 标签页数据
  const feedTabs = ref([
    {
      label: '推荐',
      type: 'recommend',
      current: 1,
      hasMore: true,
      list: [], // 每个list管理自己的数据列表
      rendered: true,
      scrollTop: 0,
    },
    {
      label: '关注',
      type: 'like',
      current: 1,
      hasMore: true,
      list: [],
      rendered: false,
      scrollTop: 0,
    },
    {
      label: '减脂',
      type: 'fatReduction',
      current: 1,
      hasMore: true,
      list: [],
      rendered: false,
      scrollTop: 0,
    },
    {
      label: '饮食',
      type: 'food',
      current: 1,
      hasMore: true,
      list: [],
      rendered: false,
      scrollTop: 0,
    },
  ])

  // 当前的tab配置对象
  const feedTab = computed(() => feedTabs.value[tabIndex.value])
  // // 当前的type
  // const feedType = computed(() => feedTab.type)
  // // 当前的页码
  // const feedCurrent = computed(() => feedTab.current)
  // // 每次请求多少条数据
  // const feedPageSize = ref(5)

  // 切换标签页
  async function onFeedTabChange({ index }) {
    tabIndex.value = index

    // 如果当前 tab 配置中的 rendered 为 false，那么就需要发一次请求
    if (!feedTab.value.rendered) {
      loadList()
    }

    // 只要点击过这个tab，就将其 是否渲染过 标记为 true
    feedTab.value.rendered = true

    await nextTick()

    curScrollTop.value = feedTab.value.scrollTop
  }

  const onScrolltolower = () => {
    console.log('onScrolltolower')
    // 加载之前，要先判断，当前列表是否还有下一页
    if (feedTab.value.hasMore) {
      loadList()
    }
  }

  const loadList = async () => {
    const res = await patientHomeKnowledgeApi({
      type: feedTab.value.type,
      current: feedTab.value.current,
      pageSize: 5,
    })

    const { pageTotal, rows } = res.data

    // 设置列表数据
    feedTab.value.list.push(...rows)

    // 判断是否还有下一页
    if (feedTab.value.current >= pageTotal) {
      feedTab.value.hasMore = false
    }

    feedTab.value.current++
  }

  onMounted(() => {
    loadList()
  })

  const onScroll = (e) => {
    console.log(`${feedTab.value.label} - ${e.detail.scrollTop}`)
    feedTab.value.scrollTop = e.detail.scrollTop
  }

  // 记录当前的scrollTop，
  const curScrollTop = ref(0)
  // 侦听 feedTab.value.scrollTop 的改变，然后延迟设置到 curScrollTop 上面

  // 问题：小程序中会抖动
  // 原因：每次滚动会触发onScroll回调，会给当前的feedTab.value.scrollTop赋值，
  //      如果再对其侦听改变，每次都会重新给curScrollTop赋值，这样就会频繁去渲染视图更新
  // 解决办法：在点击切换tab的时候，再去更新curScrollTop的值
  // watch(
  //   () => feedTab.value.scrollTop,
  //   async () => {
  //     await nextTick()
  //     // 等视图更新后，在来设置 curScrollTop 值，
  //     // 说白了，就等列表切换完后，scroll-page渲染后
  //     curScrollTop.value = feedTab.value.scrollTop
  //   }
  // )

  const recommendDoctorList = ref([])
  onMounted(async () => {
    const res = await homePageDocApi({ current: 1, pageSize: 5 })
    recommendDoctorList.value = res.data.rows
  })
</script>

<template>
  <!-- 容器目前停留在关注列表，最高也就 1342.5 -->
  <!-- 推荐 2200+ -->
  <!-- scroll-view组件会监听scrollTop属性的变化，当变更时，会触发scroll事件 -->
  <!-- 本来是停留在关注列表，最高 1342.5，但是一秒后，视图已经更新了，早已切换到推荐列表，最高就不至1342.5了 -->
  <scroll-page
    :scrollTop="curScrollTop"
    @scrolltolower="onScrolltolower"
    @scroll="onScroll"
  >
    <view
      class="index-page"
      :style="{ backgroundPositionY: -48 + safeAreaInsets.top + 'px' }"
    >
      <!-- 页面导航 -->
      <view
        :style="{ paddingTop: safeAreaInsets.top + 'px' }"
        class="page-navbar"
        >优医</view
      >

      <!-- 搜索栏 -->
      <view class="search-bar">
        <input
          placeholder-class="input-placeholder"
          placeholder="搜一搜: 疾病/症状/医生/健康知识"
          class="input"
          type="text"
        />
        <view class="icon-search">
          <uni-icons size="22" color="#C3C3C5" type="search" />
        </view>
      </view>
      <!-- 快速入口 -->
      <view class="quick-entry">
        <navigator hover-class="none" class="quick-entry-item">
          <image
            class="quick-entry-icon"
            src="/static/images/quick-entry-1.png"
          />
          <text class="label">问医生</text>
          <text class="small">按科室查问医生</text>
        </navigator>
        <navigator
          hover-class="none"
          class="quick-entry-item"
          url="/subpkg_consult/quickly/index?type=2"
        >
          <image
            class="quick-entry-icon"
            src="/static/images/quick-entry-2.png"
          />
          <text class="label">极速问诊</text>
          <text class="small">20s医生极速回复</text>
        </navigator>
        <navigator hover-class="none" class="quick-entry-item">
          <image
            class="quick-entry-icon"
            src="/static/images/quick-entry-3.png"
          />
          <text class="label">开药门诊</text>
          <text class="small">线上买药更方便</text>
        </navigator>
      </view>
      <!-- 快速查看 -->
      <view class="quick-view">
        <navigator
          hover-class="none"
          class="quick-view-item"
          url="/subpkg_medicine/order_list/index"
        >
          <image
            class="quick-view-icon"
            src="/static/images/quick-view-1.png"
          />
          <text class="label">药品订单</text>
        </navigator>
        <navigator
          hover-class="none"
          class="quick-view-item"
          url="/subpkg_archive/list/index"
        >
          <image
            class="quick-view-icon"
            src="/static/images/quick-view-2.png"
          />
          <text class="label">健康档案</text>
        </navigator>
        <navigator hover-class="none" class="quick-view-item">
          <image
            class="quick-view-icon"
            src="/static/images/quick-view-3.png"
          />
          <text class="label">我的处方</text>
        </navigator>
        <navigator hover-class="none" class="quick-view-item">
          <image
            class="quick-view-icon"
            src="/static/images/quick-view-4.png"
          />
          <text class="label">疾病查询</text>
        </navigator>
      </view>
      <!-- 广告位 -->
      <view class="banner-placeholder">
        <swiper
          class="uni-swiper"
          indicator-dots
          indicator-color="#ffffff99"
          indicator-active-color="#fff"
          circular
        >
          <swiper-item>
            <navigator hover-class="none" class="navigator" url=" ">
              <image class="banner-image" src="/static/images/banner-1.png" />
            </navigator>
          </swiper-item>
          <swiper-item>
            <navigator hover-class="none" class="navigator" url=" ">
              <image
                class="banner-image"
                src="/static/images/banner-1.png"
                mode="aspectFill"
              />
            </navigator>
          </swiper-item>
        </swiper>
      </view>
      <!-- 标签页列表 -->

      <!-- 标签切换 -->
      <view
        class="doctor-feeds"
        :style="{ marginTop: -safeAreaInsets.top + 'px' }"
      >
        <custom-sticky :offset-top="safeAreaInsets.top + 'px'">
          <custom-tabs @click="onFeedTabChange" :list="feedTabs" />
        </custom-sticky>
        <!-- 这里的 v-show 和 v-if 配合使用，实现了一个懒渲染和缓存的功能 -->
        <!-- 关注知识列表 -->
        <!-- v-show只会控制样式显示隐藏，并不会删结构 -->
        <view
          v-for="(feed, index) in feedTabs"
          :key="feed.type"
          v-show="tabIndex === index"
        >
          <DoctorList
            :list="recommendDoctorList"
            v-if="feed.type === 'recommend'"
          />
          <!-- v-if会控制结构来显示隐藏，rendered 在首页初次加载时，只有推荐是true -->
          <feed-list :list="feed.list" v-if="feed.rendered" />
        </view>
      </view>
    </view>
  </scroll-page>
</template>
<style lang="scss">
  @import './index.scss';
</style>
